package com.rudolfheszele.smsselector.controller;

import java.util.Iterator;
import java.util.LinkedList;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.rudolfheszele.smsselector.R;
import com.rudolfheszele.smsselector.model.SmsSelectorRuleSet;
import com.rudolfheszele.smsselector.view.SmsSelectorRuleCreatorActivity;
import com.rudolfheszele.smsselector.view.SmsSelectorRulesViewerActivity;
import com.rudolfheszele.smsselector.view.View;

class DeleteRuleDialogOnClickListener implements DialogInterface.OnClickListener
{
	public DeleteRuleDialogOnClickListener(String ruleName, SmsSelectorRulesViewerActivityController controller)
	{
		mMainController = (SmsSelectorMainController)ControllerFactoryFactory.getControllerFactory().getController();
		mRuleName = ruleName;
		mController = controller;
	}
	
	@Override
	public void onClick(DialogInterface dialog, int which)
	{
		if(which == DialogInterface.BUTTON_POSITIVE)
		{
			SmsSelectorRuleSet ruleSet = mMainController.getRuleSetByName(mRuleName);
			
			mMainController.removeRuleSet(ruleSet);
			mMainController.startSmsReaderService(mController);
		}
		dialog.dismiss();
	}
	
	SmsSelectorRulesViewerActivityController mController;
	SmsSelectorMainController mMainController;
	String mRuleName;
}

class SmsSelectorRulesViewerActivityProgressBarProgressUpdater implements Runnable
{
	public SmsSelectorRulesViewerActivityProgressBarProgressUpdater(ProgressDialog progressDialog, int progress)
	{
		mProgressDialog = progressDialog;
		mProgress = progress;
	}
	
	@Override
	public void run()
	{
		mProgressDialog.setProgress(mProgress);
	}
	
	private ProgressDialog mProgressDialog;
	private int mProgress;
}

class SmsSelectorRulesViewerUpdater implements Runnable
{
	public SmsSelectorRulesViewerUpdater(SmsSelectorRulesViewerActivityController smsSelectorRulesViewerActivityController)
	{
		mSmsSelectorRulesViewerActivityController = smsSelectorRulesViewerActivityController;
	}
	
	public void run()
	{
		mSmsSelectorRulesViewerActivityController.updateView(mSmsSelectorRulesViewerActivityController.getView(0));
	}
	
	private SmsSelectorRulesViewerActivityController mSmsSelectorRulesViewerActivityController;
}

// TODO: These classes do the same as in the SmsSelectorRuleCreatorActivityController.java
class SmsSelectorRulesViewerActivityProgressBarFolderUpdater implements Runnable
{
	public SmsSelectorRulesViewerActivityProgressBarFolderUpdater(ProgressDialog progressDialog, String folder)
	{
		mProgressDialog = progressDialog;
		mFolder = folder;
		mMainController = null;
	}
	
	@Override
	public void run()
	{
		Activity activity = null;
		
		mMainController = ControllerFactoryFactory.getControllerFactory().getController();
		activity = (Activity)mMainController.getView(R.layout.smsselector_rules_viewer_activity_layout);
		mProgressDialog.setMessage(activity.getString(R.string.main_activity_text_view_reading_text) + "(from " + mFolder + ")");
	}
	
	private ProgressDialog mProgressDialog;
	private String mFolder;
	private Controller mMainController;
}

public class SmsSelectorRulesViewerActivityController implements SmsReaderController, OnClickListener
{
	public SmsSelectorRulesViewerActivityController(Activity activity)
	{
		mViewerActivity = (SmsSelectorRulesViewerActivity)activity;
		mMainController = (SmsSelectorMainController)ControllerFactoryFactory.getControllerFactory().getController();
		mRuleCreatorIntent = null;
		mProgressDialog = null;
	}

	@Override
	public View getView(int viewId)
	{
		return mViewerActivity;
	}

	@Override
	public void registerView(View view)
	{
		mViewerActivity = (SmsSelectorRulesViewerActivity)view;
	}
	
	@Override
	public void updateView(View view)
	{
		clearRulesViewerActivity();
		registerRulesViewerActivity();
	}

	@Override
	public void updateGui(int viewId, Runnable task)
	{
		mViewerActivity.runOnUiThread(task);
	}
	
	@Override
	public boolean buildMenu(View view, Object menu, Object clicked)
	{
		MenuInflater inflater = mViewerActivity.getMenuInflater();
		Menu optionsMenu = (Menu)menu;
		
		if(clicked == null)
			inflater.inflate(R.menu.smsselector_rule_viewer_activity_options_menu, optionsMenu);
		else
		{
			inflater.inflate(R.menu.smsselector_rule_viewer_activity_context_menu, optionsMenu);
			((ContextMenu)menu).setHeaderTitle(mViewerActivity.getString(R.string.rule_viewer_activity_context_menu_header_text));
			mContextView = (android.view.View)clicked;
		}
		
		return true;
	}
	
	@Override
	public boolean menuClicked(View view, Object menu)
	{
		MenuItem menuItem = (MenuItem)menu;
		
		if(menuItem.getItemId() == R.id.rule_viewer_activity_options_menu_create_event_id)
		{
			mRuleCreatorIntent = new Intent(mViewerActivity, SmsSelectorRuleCreatorActivity.class);
			
			mRuleCreatorIntent.putExtra(SmsSelectorRuleCreatorActivityController.NEW_RULE, true);
			mViewerActivity.startActivity(mRuleCreatorIntent);
		}
		else
		{
			TextView textView = (TextView)mContextView;
			String ruleString = textView.getText().toString();
			String ruleName = ruleString.substring(6, ruleString.indexOf("Action") - 1);
			
			if(menuItem.getItemId() == R.id.rule_viewer_activity_delete_rule_context_menu_id)
			{
				AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(mViewerActivity);
				DeleteRuleDialogOnClickListener onClickListener = new DeleteRuleDialogOnClickListener(ruleName, this);
				AlertDialog dialog = null;
				
				dialogBuilder.setMessage("Are you sure you want to delete the rule: " + ruleName + "?");
				dialogBuilder.setCancelable(false);
				dialogBuilder.setPositiveButton("Yes", onClickListener);
				dialogBuilder.setNegativeButton("No", onClickListener);
				dialog = dialogBuilder.create();
				dialog.show();
			}
			else if(menuItem.getItemId() == R.id.rule_viewer_activity_edit_rule_context_menu_id)
			{
				mRuleCreatorIntent = new Intent(mViewerActivity, SmsSelectorRuleCreatorActivity.class);
				mRuleCreatorIntent.putExtra(SmsSelectorRuleCreatorActivityController.FROM_MESSAGE, false);
				mRuleCreatorIntent.putExtra(SmsSelectorRuleCreatorActivityController.NEW_RULE, false);
				mRuleCreatorIntent.putExtra(SmsSelectorRuleCreatorActivityController.RULE_NAME, ruleName);
				mViewerActivity.startActivity(mRuleCreatorIntent);
			}
		}
		
		return false;
	}
	
	/**
	 * @see Controller
	 */
	@Override
	public void saveState(int viewId, Object state)
	{
		// Nothing to save	
	}
	
	/**
	 * @see Controller
	 */
	@Override
	public void restoreState(int viewId, Object state)
	{
		// Nothing to restore, registering the new activity is enough
	}
	
	@Override
	public void reportProgress(ProgressState progressState, Object additionalInfo)
	{
		String directory = null;
		int progress = 0;
		
		switch(progressState)
		{
			case NEW_PROGRESS_STATE:
				progress = ((Integer)additionalInfo).intValue();
				updateGui(0, new SmsSelectorRulesViewerActivityProgressBarProgressUpdater(mProgressDialog, progress));
				break;
			case DIRECTORY_CHANGED_STATE:
				directory = (String)additionalInfo;
				updateGui(0, new SmsSelectorRulesViewerActivityProgressBarFolderUpdater(mProgressDialog, directory));
				break;
		}
	}

	@Override
	public void smsReadingFinished()
	{
		mProgressDialog.dismiss();
		mProgressDialog = null;
		// TODO: It needs to be done in the main thread...
		updateGui(0, new SmsSelectorRulesViewerUpdater(this));
	}

	@Override
	public void smsReadingStarted(SmsSelectorSmsReaderService smsReaderService)
	{
		mProgressDialog = new ProgressDialog(mViewerActivity);
		mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		mProgressDialog.setMax(100);
		mProgressDialog.setProgress(0);
		mProgressDialog.setMessage("");
		mProgressDialog.setOwnerActivity(mViewerActivity);
		mProgressDialog.show();
	}
	
	@Override
	public void onClick(android.view.View view)
	{
		TextView textView = (TextView)view;
		String ruleString = textView.getText().toString();
		String ruleName = ruleString.substring(6, ruleString.indexOf("Action") - 1);
		
		mRuleCreatorIntent = new Intent(mViewerActivity, SmsSelectorRuleCreatorActivity.class);
		mRuleCreatorIntent.putExtra(SmsSelectorRuleCreatorActivityController.FROM_MESSAGE, false);
		mRuleCreatorIntent.putExtra(SmsSelectorRuleCreatorActivityController.NEW_RULE, false);
		mRuleCreatorIntent.putExtra(SmsSelectorRuleCreatorActivityController.RULE_NAME, ruleName);
		mViewerActivity.startActivity(mRuleCreatorIntent);
	}
	
	private void registerRulesViewerActivity()
	{
		LinkedList<SmsSelectorRuleSet> ruleSets = mMainController.getRuleSets();
		Iterator<SmsSelectorRuleSet> ruleSetsIterator = ruleSets.iterator();
		LinearLayout mainlinearLayout = (LinearLayout)mViewerActivity.findViewById(R.id.rules_viewer_activity_main_linear_layout_id);
		
		// If there is no rules at all, just state it to the user...
		if(ruleSets.size() == 0)
		{
			TextView noRuleTextView = new TextView(mViewerActivity);
			
			noRuleTextView.setText("No rules have been defined yet!!!");
			mainlinearLayout.addView(noRuleTextView);
			
			return;
		}
		while(ruleSetsIterator.hasNext())
		{
			SmsSelectorRuleSet ruleSet = ruleSetsIterator.next();
			SmsSelectorRuleSet.Action action = ruleSet.getAction();
			LinkedList<SmsSelectorRuleSet.Rule> rules = ruleSet.getRules();
			Iterator<SmsSelectorRuleSet.Rule> rulesIterator = rules.iterator();
			LinkedList<SmsSelectorRuleSet.LogicalOperation> operations = ruleSet.getLogicalOperations();
			Iterator<SmsSelectorRuleSet.LogicalOperation> operationsIterator = operations.iterator();
			StringBuilder stringBuilder = new StringBuilder("Name: ");
			TextView ruleTextView = new TextView(mViewerActivity);
			android.view.View separatorView = new android.view.View(mViewerActivity);
			SmsSelectorRuleSet.Rule rule = null;
			
			stringBuilder.append(ruleSet.getName() + "\n");
			stringBuilder.append("Action: " + action.getId().getName() + " " + action.getAdditionalInfo() + "\n");
			stringBuilder.append("Rule: \n");
			
			while(operationsIterator.hasNext())
			{
				SmsSelectorRuleSet.LogicalOperation operation = operationsIterator.next();
				
				rule = rulesIterator.next();
				stringBuilder.append(rule.getId().getName() + " " + rule.getAddtitionalInfo() + " ");
				stringBuilder.append(operation.getId().getName() + " ");
			}
			// There must be one less operations than rules, so fetch the last rule
			rule = rulesIterator.next();
			stringBuilder.append(rule.getId().getName() + " " + rule.getAddtitionalInfo() + " ");
			ruleTextView.setText(stringBuilder);
			ruleTextView.setOnClickListener(this);
			separatorView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, 2));
			separatorView.setBackgroundColor(0xFF909090);
			separatorView.setPadding(0, 5, 0, 5);
			mainlinearLayout.addView(ruleTextView);
			mViewerActivity.registerForContextMenu(ruleTextView);
			mainlinearLayout.addView(separatorView);
		}
	}
	
	private void clearRulesViewerActivity()
	{
		mViewerActivity.setContentView(R.layout.smsselector_rules_viewer_activity_layout);
	}

	private SmsSelectorRulesViewerActivity mViewerActivity;
	private SmsSelectorMainController mMainController;
	private Intent mRuleCreatorIntent;
	private android.view.View mContextView;
	private ProgressDialog mProgressDialog;
}
